package com.tools.generator.service.impl;

import com.tools.common.utils.DateUtils;
import com.tools.generator.config.ToolDataSource;
import com.tools.generator.entity.DataSourceEntity;
import com.tools.generator.enums.dbEnum;
import com.tools.generator.mapper.DataSourceMapper;
import com.tools.generator.service.DataSourceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

@Slf4j
@AllArgsConstructor
@Service
public class DataSourceServiceImpl implements DataSourceService {

    private DataSourceMapper dataSourceMapper;

    private final DataSource dataSource;

    @Override
    public List<DataSourceEntity> page(DataSourceEntity query) {
        return dataSourceMapper.selectGenDatasourceList(query);
    }

    @Override
    public List<DataSourceEntity> getList() {
        return dataSourceMapper.selectGenDatasourceList(null);
    }

    @Override
    public String getDatabaseProductName(Long datasourceId) {
        if (datasourceId.intValue() == 0) {
            return dbEnum.MySQL.name();
        }
        return dataSourceMapper.selectGenDatasourceById(datasourceId).getDbType();
    }

    @Override
    public ToolDataSource get(Long datasourceId) {
        // 初始化配置信息
        ToolDataSource info = null;
        if (datasourceId.intValue() == 0) {
            try {
                info = new ToolDataSource(dataSource.getConnection());
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        info = new ToolDataSource(this.getById(datasourceId));
        return info;
    }

    @Override
    public int save(DataSourceEntity entity) {
        entity.setCreateTime(DateUtils.getNowDateTimeString());
        return dataSourceMapper.insertGenDatasource(entity);
    }

    @Override
    public DataSourceEntity getById(Long id) {
        return dataSourceMapper.selectGenDatasourceById(id);
    }

    @Override
    public void updateById(DataSourceEntity entity) {
        dataSourceMapper.updateGenDatasource(entity);
    }

    @Override
    public void removeBatchByIds(List<Long> list) {
        dataSourceMapper.deleteGenDatasourceByIds(list);
    }
}
